import { Button, NavBar, Form, Input, Toast, InputRef } from "antd-mobile";
import { useDispatch } from "react-redux";
import { fetchLogin } from "@/store/modules/userSlice";
// import { getCodeApi } from "@/apis/login";
import { useNavigate } from "react-router-dom";

import styles from "./index.module.scss";
import { AppDispatch } from "@/types/store";
import { AxiosError } from "axios";
import { useEffect, useRef, useState } from "react";

const Login = () => {
  const rules = {
    mobile: [
      { required: true, message: "请输入手机号" },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: "手机号格式错误",
      },
    ],
    code: [{ required: true, message: "请输入验证码" }],
  };
  const [form] = Form.useForm();

  const dispatch = useDispatch<AppDispatch>();
  const navigate = useNavigate();
  const onFinish = async (values: LoginParams) => {
    try {
      await dispatch(fetchLogin(values));
      Toast.show({
        content: "登录成功",
        duration: 600,
        afterClose: () => {
          navigate("/home");
        },
      });
    } catch (e) {
      const error = e as AxiosError<{ message: string }>;
      Toast.show({
        content: error.response?.data?.message,
        duration: 1000,
      });
    }
  };

  const [timeLeft, setTimeLeft] = useState(0);
  const mobileRef = useRef<InputRef>(null);
  const codeRef = useRef<InputRef>(null);
  const timer = useRef<number | undefined>(undefined);
  
  const getCaptcha = async () => {
    if (timeLeft) return;
    if (form.getFieldError("mobile").length > 0) {
      mobileRef.current?.focus();
      return;
    }
    // const mobile = form.getFieldValue("mobile");
    // await getCodeApi(mobile)
    setTimeLeft(5);
    timer.current = window.setInterval(() => {
      setTimeLeft(timeLeft => {
        if(timeLeft <= 1 && timer.current !== undefined) {
          clearInterval(timer.current)
          timer.current = undefined;
          console.log("清除定时器");
        };
        return timeLeft - 1
      });
    }, 1000);
    Toast.show({
      content: "验证码已发送",
      duration: 500,
    });
    form.setFieldValue("code", "");
    codeRef.current?.focus();
  };
  useEffect(() => () => {
    if(timer.current!== undefined) {
      clearInterval(timer.current)
      timer.current = undefined;
      console.log("清除定时器");
    }
  }, [])
  return (
    <div className={styles.root}>
      <NavBar onBack={() => { navigate(-1); }}></NavBar>

      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form
          form={form}
          onFinish={onFinish}
          initialValues={{
            mobile: "13911111111",
            code: "246810",
          }}
        >
          <Form.Item
            name="mobile"
            className="login-item"
            rules={rules.mobile}
            validateTrigger="onBlur"
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="code"
            className="login-item"
            extra={
              <span className="code-extra" onClick={getCaptcha}>
                {timeLeft ? `${timeLeft}s后重新获取` : "发送验证码"}
              </span>
            }
            rules={rules.code}
            validateTrigger="onBlur"
          >
            <Input placeholder="请输入验证码" autoComplete="off" />
          </Form.Item>

          {/* noStyle 表示不提供 Form.Item 自带的样式 */}
          <Form.Item noStyle shouldUpdate>
            {() => {
              return (
                <Button
                  block
                  type="submit"
                  color="primary"
                  // disabled={
                  //   !form.isFieldsTouched(true) ||
                  //   form
                  //     .getFieldsError()
                  //     .some(({ errors }) => errors.length > 0)
                  // }
                  className="login-submit"
                >
                  登 录
                </Button>
              );
            }}
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
